﻿using System.Windows.Input;
using System.Windows.Interactivity;
using System.Windows.Controls;

namespace Client.Behaviors
{
    public class SelectAllTextOnFocusBehavior : Behavior<Control>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.GotKeyboardFocus += AssociatedObjectGotKeyboardFocus;
            AssociatedObject.GotMouseCapture += AssociatedObjectGotMouseCapture;
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.GotKeyboardFocus -= AssociatedObjectGotKeyboardFocus;
            AssociatedObject.GotMouseCapture -= AssociatedObjectGotMouseCapture;
        }

        private void AssociatedObjectGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            if(AssociatedObject is TextBox)
            {
                ((TextBox) AssociatedObject).SelectAll();
            }
            else if (AssociatedObject is PasswordBox)
            {
                ((PasswordBox)AssociatedObject).SelectAll();
            }
        }

        private void AssociatedObjectGotMouseCapture(object sender, MouseEventArgs e)
        {
            if (AssociatedObject is TextBox)
            {
                ((TextBox)AssociatedObject).SelectAll();
            }
            else if (AssociatedObject is PasswordBox)
            {
                ((PasswordBox)AssociatedObject).SelectAll();
            }
        }
    } 
}
